﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.ApplicationBlocks.Data ;
using TransportManager.UI.Pages ;
using System.Data.SqlClient;

namespace Site.Report
{
    public partial class checkin : BasePage
    {
        protected System.Data.DataTable dt, dt0;
        protected String Sqlstr; 
        double a;
       
        int row;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            this.Button4.Click += new System.EventHandler(this.Button4_Click);
            this.drpType.SelectedIndexChanged += new System.EventHandler(this.drpType_SelectedIndexChanged);
            this.Button3.Click += new System.EventHandler(this.Button3_Click);
            this.Button2.Click += new System.EventHandler(this.Button2_Click);
            this.Button6.Click += new System.EventHandler(this.Button6_Click);
            this.Button1.Click += new System.EventHandler(this.Button1_Click);


            if (Session.Count < 2)
            {
                Response.Write("请登陆");
                Response.End();
            }

            //	SetButtonAttributes("入库？",btnInDb,false);
            if (Page.IsPostBack) return;
            /*if(Session["name"].ToString().Trim()!="蒋菠")
            {
                Button6.Visible = false;
                dg.Columns[9].Visible = false;
            }*/

            tbdate.Text = System.DateTime.Now.ToShortDateString();


            Sqlstr = "delete productInBill where billnumber not in(select billnumber from productInBill_Detail)";
            Sqlstr += " select code,name from CodeBigType where len(code)=1";
            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            drpType.DataSource = dt.DefaultView;
            drpType.DataBind();
            if (Request.QueryString.Count > 0)
            {
                tbbillNumber.Text = Request.QueryString[0];
                Button2_Click(null, null);

            }
            else
                Button3_Click(null, e);

        }



        protected void Button1_Click(object sender, System.EventArgs e)
        {

            if (btnInDb.Enabled == false)
            {
                ResponseMsg("该单已经入库，如果该记录入错请马上删除！");
                //return;
            }

            if (tbBuyer.Text == "")
            {
                ResponseMsg("购买人必填");
                return;
            }
            if (ProductSearch1.productcode.Trim() == "")
            {
                ResponseMsg("请选择物料！");
                return;
            }
            if (tbfactamount.Text.Trim() == "")
            {
                ResponseMsg("请输入实际数量");
                return;
            }

            if (ProductSearch1.productcode.Substring(0, 1) != drpType.SelectedValue)
            {
                ResponseMsg("你选择的物料和类型不一致！");
                return;
            }


            Sqlstr = "if not exists(select * from productInBill where billnumber='" + tbbillNumber.Text.Trim() + "')";
            Sqlstr += " insert into productInBill(ApplyCorp,projectProduct,billnumber,billdate,billmaker,abstract,buyer)values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
            Sqlstr += " else update productInBill set ApplyCorp='{0}',projectProduct='{1}',billnumber='{2}',billdate='{3}',billmaker='{4}',abstract='{5}',buyer='{6}' where billnumber='" + tbbillNumber.Text.Trim() + "'";
            Sqlstr = string.Format(Sqlstr,
                tbApplyDep.Text,
                tbProjectReady.Text,
                tbbillNumber.Text,
                tbdate.Text,
                Session["name"].ToString(),
                tbAbstract.Text,
                tbBuyer.Text
                );
            Sqlstr += " if not exists(select * from productInBill_Detail where billnumber='{0}' and productnumber='{1}')";
            Sqlstr += " begin insert into productInBill_Detail(billnumber,productnumber,shouldamount,factamount,unitprice,factmoney,memo)values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
            //Sqlstr += " else update productInBill_Detail set shouldamount='{2}',factamount='{3}',unitprice='{4}',factmoney='{5}',memo='{6}' where billnumber='{0}'and productnumber='{1}'";
            Sqlstr += " select 1 end else select 2";
            Sqlstr = string.Format(Sqlstr,
                tbbillNumber.Text,
                ProductSearch1.productcode,
                tbShouldAmount.Text,
                tbfactamount.Text,
                tbfactunit.Text,
                tbfactMoney.Text,
                tbMemo.Text
                );

            if (btnInDb.Enabled == false)//在已经入库的单中增加项
            {
                //该记录要入库！
                //写入月报表
                Sqlstr += " if not exists(select * from caiwuMonthreport where corpcode='{0}' and dates='{1}' and productnumber='{2}')";
                Sqlstr += "  insert into caiwuMonthreport(corpcode,dates,productnumber,thisin,thisinmoney,thisrest,thisrestmoney)values('{0}','{1}','{2}','{3}','{4}','{3}','{4}')";

                Sqlstr += " else  update caiwuMonthreport set thisin=thisin+{3},thisinmoney=thisinmoney+{4},thisrest=thisrest+{3},thisrestmoney=thisrestmoney+{4} where corpcode='{0}' and dates='{1}' and productnumber='{2}' ";

                Sqlstr = string.Format(Sqlstr,
                    Session["Depcode"].ToString(),
                    FirstDay(DateTime.Parse(tbdate.Text).ToShortDateString()),
                    //dt.Rows[i]["productnumber"].ToString(),
                    ProductSearch1.productcode,
                    //dt.Rows[i]["factamount"].ToString(),
                    tbfactamount.Text,
                    //dt.Rows[i]["factmoney"].ToString(),
                    tbfactMoney.Text,
                    NextDay(DateTime.Parse(tbdate.Text).ToShortDateString())
                    );

            }
            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            if (dt.Rows[0][0].ToString() == "2")
            {
                ResponseMsg("编号为" + ProductSearch1.productcode + "的材料已开出，请确认数量！"); return;

            }
            //ResponseMsg("新增成功！");
            binding();
        }

        protected void Button6_Click(object sender, System.EventArgs e)
        {
            Sqlstr = string.Format("update productInBill set ApplyCorp='{0}',buyer='{1}' where billnumber='{2}'",
                tbApplyDep.Text, tbBuyer.Text, tbbillNumber.Text);
            SqlHelper.ExecuteNonQuery(Session["Conn"].ToString(), CommandType.Text, Sqlstr);
            ResponseMsg("修改成功！");


        }
        protected void binding()
        {
            Sqlstr = "SELECT a.number, a.productname + '(' + a.Specs + ')[' + a.unit + ']' AS productname,b.shouldamount, b.factamount, b.unitprice, b.factmoney, b.memo,b.thisid FROM CodeProductType a INNER JOIN productInBill_Detail b ON a.number = b.productnumber where b.billnumber='" + tbbillNumber.Text + "' order by thisid";
            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            dg.DataSource = dt.DefaultView;
            dg.DataBind();
            //gv.DataSource = dt.DefaultView;
            //gv.DataBind();
        }

        protected void Button2_Click(object sender, System.EventArgs e)
        {
            Sqlstr = "select * from productInBill where billnumber='" + tbbillNumber.Text + "' ";
            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            if (dt.Rows.Count == 0)
            {
                ResponseMsg("你查的单号不存在！");
                return;
            }
            if (dt.Rows[0]["checkperson"].ToString() == "0")
            {
                btnInDb.Enabled = false;
                Button1.Enabled = false;
            }
            else
            {
                btnInDb.Enabled = true;
                Button1.Enabled = true;
            }

            tbApplyDep.Text = dt.Rows[0]["ApplyCorp"].ToString();
            tbProjectReady.Text = dt.Rows[0]["ProjectProduct"].ToString();
            tbAbstract.Text = dt.Rows[0]["abstract"].ToString();
            tbdate.Text = dt.Rows[0]["billdate"].ToString();
            tbBuyer.Text = dt.Rows[0]["buyer"].ToString();
            binding();

        }

        protected void Button4_Click(object sender, System.EventArgs e)
        {
            Response.Redirect("CheckInList.aspx");
        }

        protected void Button3_Click(object sender, System.EventArgs e)
        {
            int y = (System.DateTime.Parse(tbdate.Text)).Year;
            int m = (System.DateTime.Parse(tbdate.Text)).Month;
            String billNo = "";
            if (m < 10)
                billNo = drpType.SelectedValue.Trim() + y.ToString() + "0" + m.ToString();
            else billNo = drpType.SelectedValue.Trim() + y.ToString() + m.ToString();
            Sqlstr = "select max(billnumber) from productInBill where billnumber like '" + billNo + "%'";

            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            if (dt.Rows[0][0].ToString() == "")
                billNo += "0001";
            else
            {
                Sqlstr = dt.Rows[0][0].ToString();
                int no = int.Parse(Sqlstr.Substring(7, Sqlstr.Length - 7)) + 1;
                if (no < 10)
                    billNo += "000" + no.ToString();
                else if (no < 100)
                    billNo += "00" + no.ToString();
                else if (no < 1000)
                    billNo += "0" + no.ToString();
            }
            tbbillNumber.Text = billNo;

            btnInDb.Enabled = true;
            Button1.Enabled = true;
            tbApplyDep.Text = "";
            tbBuyer.Text = "";
        }



        protected void dg_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            //如果去了财务就删除不了
            Sqlstr = "select * from productInBill_Detail where caiwutime is not null and thisid=" + dg.DataKeys[e.Item.ItemIndex].ToString();

            if (SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0].Rows.Count > 0)
            {
                ResponseMsg("去了财务就删除不了！");

            }
            else
            {
                Sqlstr = "select * from productInBill where billnumber='" + tbbillNumber.Text + "' and checkperson='0' ";
                dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];

                Sqlstr = " delete productInBill_Detail where  thisid=" + dg.DataKeys[e.Item.ItemIndex].ToString();
                if (dt.Rows.Count > 0)//已经入了总仓就减数
                {
                    Sqlstr += string.Format("  update caiwuMonthreport set thisin=thisin-({3}),thisinmoney=thisinmoney-({4}),thisrest=thisrest-({3}),thisrestmoney=thisrestmoney-({4}) where corpcode='{0}' and dates='{1}' and productnumber='{2}'",
                        "2000",
                        FirstDay(dt.Rows[0]["checktime"].ToString()),
                        e.Item.Cells[1].Text,
                        e.Item.Cells[4].Text,
                        e.Item.Cells[6].Text);
                }

                SqlTransaction trans;
                SqlConnection conn = new SqlConnection(Session["Conn"].ToString());
                conn.Open();
                trans = conn.BeginTransaction();
                try
                {
                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, Sqlstr);
                    trans.Commit();
                    ResponseMsg("删除成功！");
                }
                catch
                {
                    //Response.Write(Sqlstr);
                    trans.Rollback();
                    ResponseMsg("删除不成功！");
                }
            }

            binding();

        }
        protected void dg_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            //如果去了财务就删除不了
            Sqlstr = " select * from productInBill_Detail where caiwutime is not null and thisid=" + dg.DataKeys[e.Item.ItemIndex].ToString();
            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            if (SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0].Rows.Count > 0)
            {
                ResponseMsg("去了财务就编辑不了！");
                binding();
                return;
            }

            Sqlstr = "select * from productInBill where billnumber='" + tbbillNumber.Text + "' and checkperson='0' ";
            dt0 = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            if (dt0.Rows.Count > 0)//dt修改成为dt0已经入了总仓修改库存
            {
                Sqlstr = string.Format("update caiwuMonthreport set thisin=thisin+({3}),thisinmoney=thisinmoney+({4}),thisrest=thisrest+({3}),thisrestmoney=thisrestmoney+({4}) where corpcode='{0}' and dates='{1}' and productnumber='{2}'",
                "2000",
                FirstDay(dt0.Rows[0]["checktime"].ToString()),
                e.Item.Cells[1].Text,
                (float.Parse(((TextBox)e.Item.Cells[4].Controls[0]).Text) - float.Parse(dt.Rows[0]["factamount"].ToString())).ToString(),
                (float.Parse(((TextBox)e.Item.Cells[6].Controls[0]).Text) - float.Parse(dt.Rows[0]["factmoney"].ToString())).ToString());

            }
            else Sqlstr = "";
            Sqlstr += string.Format(" update productInBill_Detail set factamount={0},unitprice={1},factmoney={2}  where thisid=" + dg.DataKeys[e.Item.ItemIndex].ToString(),
                ((TextBox)e.Item.Cells[4].Controls[0]).Text,
                ((TextBox)e.Item.Cells[5].Controls[0]).Text,
                ((TextBox)e.Item.Cells[6].Controls[0]).Text
                );

            SqlTransaction trans;
            SqlConnection conn = new SqlConnection(Session["Conn"].ToString());
            conn.Open();
            trans = conn.BeginTransaction();
            try
            {
                SqlHelper.ExecuteNonQuery(trans, CommandType.Text, Sqlstr);
                trans.Commit();
                ResponseMsg("编辑成功！");
            }
            catch
            {
                Response.Write(Sqlstr);
                trans.Rollback();
                ResponseMsg("编辑不成功！");
            }

            dg.EditItemIndex = -1;
            binding();
        }
        protected void dg_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                a += double.Parse(e.Item.Cells[5 + 1].Text);
                e.Item.Cells[0].Text = (++row).ToString();
            }
            else if (e.Item.ItemType == ListItemType.Footer)
                e.Item.Cells[5 + 1].Text = a.ToString();

        }

        private void drpType_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            Button3_Click(null, null);
        }

        protected void dg_EditCommand_test(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            dg.EditItemIndex = e.Item.ItemIndex;
            binding();
        }

        protected void dg_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            dg.EditItemIndex = -1;
            binding();
        }

        protected void btnInDb_Click(object sender, EventArgs e)
        {
            Sqlstr = "select * from productInBill_Detail where billnumber='" + tbbillNumber.Text + "'";
            dt = SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, Sqlstr).Tables[0];
            Sqlstr = String.Empty;
            String checkTime="2012-06-29 10:35:00";
            checkTime = DateTime.Now.ToString();
            if (dt.Rows.Count > 0 && SqlHelper.ExecuteDataset(Session["Conn"].ToString(), CommandType.Text, "select * from productInBill where billnumber='" + tbbillNumber.Text + "' and checkperson is null").Tables[0].Rows.Count > 0)
            {
                Sqlstr = "update productInBill set checkperson='0',checktime='"+ checkTime+"'  where billnumber='" + tbbillNumber.Text + "' ";
              
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    //写入月报表
                    Sqlstr += " if not exists(select * from dbo.caiwuMonthreport where corpcode='{0}' and dates='{1}' and productnumber='{2}')";
                    Sqlstr += "  insert into dbo.caiwuMonthreport(corpcode,dates,productnumber,thisin,thisinmoney,thisrest,thisrestmoney)values('{0}','{1}','{2}','{3}','{4}','{3}','{4}')";

                    //原来Sqlstr +="  begin insert into caiwuMonthreport(corpcode,dates,productnumber,thisin,thisinmoney,thisrest,thisrestmoney)values('{0}','{1}','{2}','{3}','{4}','{3}','{4}')";
                    //原来Sqlstr +="  insert into caiwuMonthreport(corpcode,dates,productnumber,thisstart,thisstartmoney,thisrest,thisrestmoney)values('{0}','{5}','{2}','{3}','{4}','{3}','{4}') end";
                    Sqlstr += " else  update dbo.caiwuMonthreport set thisin=thisin+{3},thisinmoney=thisinmoney+{4},thisrest=thisrest+{3},thisrestmoney=thisrestmoney+{4} where corpcode='{0}' and dates='{1}' and productnumber='{2}' ";
                    //Sqlstr += "  update caiwuMonthreport set thisstart=thisstart+{3},thisstartmoney=thisstartmoney+{4}, thisrest=thisrest+{3},thisrestmoney=thisrestmoney+{4} where corpcode='{0}' and dates>'{1}' and productnumber='{2}' end";
                    Sqlstr = string.Format(Sqlstr,
                        Session["Depcode"].ToString(),
                        FirstDay(DateTime.Today.AddMonths(0).ToShortDateString()),
                        dt.Rows[i]["productnumber"].ToString(),
                        dt.Rows[i]["factamount"].ToString(),
                        dt.Rows[i]["factmoney"].ToString(),
                        NextDay(DateTime.Today.AddMonths(0).ToShortDateString())
                        );
                }
            }

            if (Sqlstr != string.Empty)
            {
                SqlTransaction trans;
                SqlConnection conn = new SqlConnection(Session["Conn"].ToString());
                conn.Open();
                trans = conn.BeginTransaction();
                try
                {

                    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, Sqlstr);
                    trans.Commit();
                    ResponseMsg("入库成功！");


                    btnInDb.Enabled = true;
                    Button1.Enabled = true;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                    ResponseMsg("入库不成功！");
                }

            }
            else
                ResponseMsg("该操作被取消！");





            Button3_Click(null, null);
        }

        protected void dg_EditCommand(object source, DataGridCommandEventArgs e)
        {
            dg_EditCommand_test(source, e);
        }



    }
}